package com.lizardmind.haofudoctor.ui.studio.gongGao

import android.annotation.SuppressLint
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import com.google.gson.Gson
import com.linxiao.framework.activity.BaseActivity
import com.linxiao.framework.adapter.BaseAdapter
import com.linxiao.framework.util.fromJson
import com.linxiao.framework.util.getDataBinding
import com.linxiao.framework.util.toasts
import com.lizardmind.haofudoctor.R
import com.lizardmind.haofudoctor.databinding.ActivityMenZhenDataSetBinding
import com.lizardmind.haofudoctor.databinding.ItemMenZhenTimeBinding
import com.lizardmind.haofudoctor.manager.postApi
import com.lizardmind.haofudoctor.other.*
import io.reactivex.functions.Consumer
import kotlinx.android.synthetic.main.activity_men_zhen_data_set.*
import kotlinx.android.synthetic.main.include_title_right_text.*
import org.jetbrains.anko.sdk25.coroutines.onClick
import org.jetbrains.anko.textColor
import org.json.JSONObject
import android.os.Handler
import android.os.Message
import com.bigkoo.pickerview.OptionsPickerView
import com.linxiao.framework.util.ke
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import org.json.JSONArray
import org.jetbrains.anko.toast


class MenZhenDataSetActivity : BaseActivity() {
    private val listWeek= arrayListOf("周一","周二","周三","周四","周五","周六","周日")
    private val list= arrayListOf<ArrayList<Int>>()

//    private lateinit var provinceStr:String
    private var isParsed=false
    private val options1Items = ArrayList<ProvinceBean>()
    private val options2Items = ArrayList<ArrayList<String>>()
    private val options3Items = ArrayList<ArrayList<ArrayList<String>>>()

    val adapter by lazy { BaseAdapter<ArrayList<Int>,ItemMenZhenTimeBinding>(R.layout.item_men_zhen_time,list) }

    val binding by lazy { getDataBinding<ActivityMenZhenDataSetBinding>(R.layout.activity_men_zhen_data_set) }
    override fun onCreatRootView(): View? {
        return binding.root
    }

    override fun onInitView(savedInstanceState: Bundle?) {
        imgLeft.setImageResource(R.mipmap.back)
        imgLeft.onClick { finish() }
        titleText.text="设置门诊信息"
        tvRight.text="保存"
        tvRight.textColor=ContextCompat.getColor(this,R.color.notice_red)
        tvRight.onClick {
            if (!etHospitalData.text.isEmpty()&&!etDetailAddress.text.isEmpty()&&!etContactWay.text.isEmpty()){
                postMenZhenData()
            }else{
                toasts("请将信息补充完整")
            }
        }
        tvChooseAddress.onClick {
            if (isParsed){
                showAdressPicker()
            }

        }

        adapter.headerView=LayoutInflater.from(this).inflate(R.layout.head_men_zhen_time,lLayoutMenZhenDataSet,false)
        rvMenZhenTime.apply {
            layoutManager=LinearLayoutManager(this@MenZhenDataSetActivity)
            adapter=this@MenZhenDataSetActivity.adapter
        }

        adapter.onBind { itemBingding, position, data ->
            itemBingding.cbMenZhen1.setOnCheckedChangeListener { compoundButton, b ->
                list[position][1]=if(b) 1 else 0
            }
            itemBingding.cbMenZhen2.setOnCheckedChangeListener { compoundButton, b ->
                list[position][2]=if(b) 1 else 0
            }
            itemBingding.cbMenZhen3.setOnCheckedChangeListener { compoundButton, b ->
                list[position][3]=if(b) 1 else 0
            }

        }

        for (i in 0 until listWeek.size){
            list.add(arrayListOf())
            for (j in 0..3){
                list[i].add(if (j==0) i else 0)
            }
        }

        getMenZhenData()

       Thread(){
           kotlin.run {
               initJsonData("ProvinceBean.json")
           }
       }.start()

    }

    private val mHandler = @SuppressLint("HandlerLeak")
    object : Handler() {

        override fun handleMessage(msg: Message) {
            when (msg.what) {
                1 -> {
                    isParsed = true
                }
                0 -> toast("解析省市数据失败")
            }
        }
    }

    private fun getMenZhenData(){
        observe {
            postApi<Request<MenZhenDataBean>>(
                    hashMapOf("action" to "men",
                            "token" to DoctorInfo.token),
                    Consumer {
                        it.dispose {
                            if (!it.hospital.isEmpty()){
                                etHospitalData.setText(it.hospital)
                                etDetailAddress.setText(it.address)
                                etContactWay.setText(it.way)
                                list.clear()
                                list.addAll(Gson().fromJson<ArrayList<ArrayList<Int>>>(it.service_time))
                                adapter.notifyDataSetChanged()
                            }
                        }
                    },context = this@MenZhenDataSetActivity)
        }

    }

    private fun postMenZhenData(){
        val json=JSONObject()
        json.put("hospital",etHospitalData.text.toString())
        json.put("address",etDetailAddress.text.toString())
        json.put("way",etContactWay.text.toString())
        json.put("service_time",list.toString())

        observe {
            postApi<Request<String>>(
                    hashMapOf("action" to "edit_men",
                            "token" to DoctorInfo.token,
                            "data" to json.formatToZY()),
                    Consumer {
                        it.dispose {
                            toasts(it)
                            finish()
                        }
                    },context = this@MenZhenDataSetActivity)
        }

    }

    //show地址选择picker
    private fun showAdressPicker(){
        val provincePicker=OptionsPickerView.Builder(this,OptionsPickerView.OnOptionsSelectListener {
            options1, options2, options3, v ->

            val tx = options1Items[options1].pickerViewText +
                    options2Items[options1][options2] +
                    options3Items[options1][options2][options3]
            etDetailAddress.setText(tx)

        }).setTitleText("城市选择")
                .setTextColorCenter(ContextCompat.getColor(this,R.color.gray3))
                .setContentTextSize(20)
                .build()
        provincePicker.setPicker(options1Items, options2Items,options3Items);//三级选择器
        provincePicker.show();
    }

    private fun initJsonData(fileName:String){//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         */
        val JsonData = getProvinceJson(fileName)//获取assets目录下的json文件数据
        ke(JsonData)
        val jsonBean = parseData(JsonData)//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items.clear()
        options1Items.addAll(jsonBean)

        for (i in 0 until jsonBean.size) {//遍历省份
            val CityList = ArrayList<String>()//该省的城市列表（第二级）
            val Province_AreaList = ArrayList<ArrayList<String>>()//该省的所有地区列表（第三极）

            for (c in 0 until jsonBean.get(i).city.size) {//遍历该省份的所有城市
                val CityName = jsonBean.get(i).city[c].name
                CityList.add(CityName)//添加城市

                val City_AreaList = ArrayList<String>()//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).city[c].area == null || jsonBean[i].city[c].area.size === 0) {
                    City_AreaList.add("")
                } else {

                    for (d in 0 until jsonBean.get(i).city[c].area.size) {//该城市对应地区所有数据
                        val AreaName = jsonBean.get(i).city[c].area[d]

                        City_AreaList.add(AreaName)//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList)//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList)

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList)
        }

        mHandler.sendEmptyMessage(1)

    }
    private fun parseData(result: String): List<ProvinceBean> = Gson().fromJson<List<ProvinceBean>>(result)
    //读取文件返回省市json
    private fun getProvinceJson( fileName: String): String {

        val stringBuilder = StringBuilder()
        try {
            val assetManager = this.assets
            val bf = BufferedReader(InputStreamReader(assetManager.open(fileName)))
            val s = bf.use { it.lineSequence().joinToString("") }
            bf.close()
            return s
        } catch (e: IOException) {
            e.printStackTrace()
        }

        return stringBuilder.toString()
    }

}
